package com.szlanyou.thirdsdk.retrofit.interceptor;

import com.szlanyou.thirdsdk.retrofit.client.ClientCommonParamsManager;
import com.szlanyou.thirdsdk.retrofit.util.MyLogUtil;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author: 陈章 on 2016/6/21 0021.
 * function:
 * 拦截添加HttpClient的公共头字段
 * 2021.7.19 Deprecated:改在单次请求里实现
 */
@Deprecated
public class HeaderAttachInterceptor implements Interceptor {
    private static final String TAG = "HeaderAttachInterceptor";
    private ClientCommonParamsManager clientCommonParamsManager;

    public HeaderAttachInterceptor(ClientCommonParamsManager clientCommonParamsManager) {
        this.clientCommonParamsManager = clientCommonParamsManager;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        StringBuilder commonParamsLogInfo = new StringBuilder();
        commonParamsLogInfo.append("公共请求头\n");

        for (Iterator<Map.Entry<String,Object>> it = clientCommonParamsManager.getCommonHeaders().entrySet().iterator(); it.hasNext();){
            Map.Entry<String, Object> item = it.next();
            String key = item.getKey();
            Object value = item.getValue();
            if(null != value){
                builder.addHeader(key, String.valueOf(value));
                commonParamsLogInfo.append(String.format("key = %s,value = %s\n",key,value));
            }else{
                MyLogUtil.d("HeaderAttachInterceptor:the value for key【" + key + "】is null");
            }
        }
        if(clientCommonParamsManager.getCommonHeaders().size() > 0){
            MyLogUtil.d(TAG,commonParamsLogInfo.toString());
        }

        Request request = builder.build();
        return chain.proceed(request);
    }
}